# log_module.py
import logging
import sys
import time
from typing import Dict
from PyQt6.QtCore import QObject, pyqtSignal, Qt
from PyQt6.QtGui import QColor

class QtHandler(QObject, logging.Handler):
    """自定义Qt日志处理器"""
    log_signal = pyqtSignal(str)  # 用于跨线程日志传递的信号

    def __init__(self, text_browser):
        super().__init__()
        self.text_browser = text_browser
        self.level_colors: Dict[int, str] = {
            logging.DEBUG: "#666666",     # 灰色
            logging.INFO: "#009900",     # 绿色
            logging.WARNING: "#FFA500",  # 橙色
            logging.ERROR: "#FF0000",    # 红色
            logging.CRITICAL: "#8B0000"  # 深红
        }
        self.setFormatter(logging.Formatter(
            "[%(asctime)s] [%(levelname)s] [%(filename)s:%(lineno)d] - %(message)s"
        ))
        self.log_signal.connect(self._append_log)

    def emit(self, record):
        """重写emit方法"""
        msg = self.format(record)
        color = self.level_colors.get(record.levelno, "#000000")
        html = f'<div style="color: {color}; margin: 2px;">{msg}</div>'
        self.log_signal.emit(html)  # 通过信号保证线程安全

    def _append_log(self, html: str):
        """实际追加日志到文本框"""
        self.text_browser.append(html)
        self.text_browser.ensureCursorVisible()  # 自动滚动到底部

        # 限制最大行数（可选）
        max_lines = 1000
        if self.text_browser.document().lineCount() > max_lines:
            cursor = self.text_browser.textCursor()
            cursor.movePosition(cursor.MoveOperation.Start)
            cursor.movePosition(cursor.MoveOperation.Down, cursor.MoveMode.KeepAnchor, 100)
            cursor.removeSelectedText()

class QtLogger:
    """日志模块封装类"""
    def __init__(self, text_browser, level=logging.DEBUG):
        self.handler = QtHandler(text_browser)
        self._setup_logging(level)

    def _setup_logging(self, level):
        """配置日志系统"""
        logging.basicConfig(level=level)
        logger = logging.getLogger()
        logger.handlers.clear()  # 移除默认处理器
        logger.addHandler(self.handler)

    @staticmethod
    def set_level(level: int):
        """设置日志级别"""
        logging.getLogger().setLevel(level)

    @staticmethod
    def get_logger(name: str = None) -> logging.Logger:
        """获取日志记录器"""
        return logging.getLogger(name)